package com.xidian.zhiancloud.controller.accidentManage;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xidian.zhiancloud.constant.AccidentManagementConstant;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.MissAccidentMessage;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.accidentmessage.MissAccidentQO;
import com.xidian.zhiancloud.service.accidentManage.MissAccidentService;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.util.zyf.ExcelUtils;
import com.xidian.zhiancloud.vo.accidentmessage.AccidentMessageVO;
import com.xidian.zhiancloud.vo.accidentmessage.MissAccidentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName MissAccidentMessageController
 * @Description 未遂事件信息管理接口
 * @Author zc
 **/
@RestController
@RequestMapping("/missAccidentMsg")
public class MissAccidentController extends BaseController {

    @Resource
    private MissAccidentService missAccidentService;

    @Resource
    private UserService userService;

    @Resource
    private OrganizationService organizationService;

    /**
     * 添加未遂事件
     * @param missAccidentMessage 未遂事件基本信息
     * @return 返回是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> addMissAccident(MissAccidentMessage missAccidentMessage){
        missAccidentMessage.setCompanyId(getSessionUserCompanyId());
        missAccidentMessage.setCreator(getSessionUserid());
        missAccidentMessage.setCreateTime(new Date(System.currentTimeMillis()));
        missAccidentService.save(missAccidentMessage);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 删除未遂事件信息
     * @param ids 未遂事件id数组
     * @return 返回是否删除成功
     */
    @PostMapping("/delete")
    public ResultDTO<Boolean> deleteMissAccident(Long[] ids){
        missAccidentService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id获取未遂事件信息
     * @param id 未遂事件id
     * @return 返回未遂事件实体
     */
    @GetMapping("/get")
    public ResultDTO<MissAccidentMessage> getMsgById(Long id){
        return ResultDTO.successOf(missAccidentService.getById(id),GeneralResponseEnums.SUCCESS);
    }

    /**
     * 修改未遂事件信息
     * @param missAccidentMessage 未遂事件实体
     * @return 返回是否修改成功
     */
    @PostMapping("/patch")
    public ResultDTO<Boolean> updateMissAccidentMsg(MissAccidentMessage missAccidentMessage){
        missAccidentMessage.setCompanyId(null);
        missAccidentMessage.setCreator(null);
        missAccidentMessage.setCreateTime(null);
        missAccidentService.updateById(missAccidentMessage);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 条件查询 部门id，事故发生时间，关键字
     * @param missAccidentQO 请求实体类
     * @return 返回查询结果列表
     */
    @GetMapping("/list")
    public ResultDTO<IPage<MissAccidentVO>> getListByQO(MissAccidentQO missAccidentQO){
        if(missAccidentQO.getCurrent() == null || missAccidentQO.getSize() == null){
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }

        missAccidentQO.setCompanyId(getSessionUserCompanyId());
        IPage<MissAccidentVO> list = missAccidentService.getListByQO(missAccidentQO);
        return ResultDTO.successOf(list,GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     * @param response
     * @param ids 未遂事件id
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response,Long[] ids)throws IOException{
        if(ids == null || ids.length==0){
            return;
        }

        List<MissAccidentMessage> list = missAccidentService.listByIds(Arrays.asList(ids));
        List<MissAccidentVO> new_list = new ArrayList<>();

        list.forEach(obj -> {
            MissAccidentVO vo = new MissAccidentVO();
            BeanUtils.copyProperties(obj,vo);

            vo.setMainCauseStr(AccidentManagementConstant.MainCause.get(vo.getMainCause()));

            if(vo.getDeviceFactor() != null){
                String[] arr = vo.getDeviceFactor().split(",");
                String factors = "";
                for (String s : arr) {
                    String factor = AccidentManagementConstant.DeviceFactor.get(Integer.parseInt(s));
                    factors += factor;
                    factors += ",";
                }
                vo.setDeviceFactorStr(factors);
            }

            if(vo.getEnvironmentFactor() != null){
                String[] arr = vo.getEnvironmentFactor().split(",");
                String factors = "";
                for (String s : arr) {
                    String factor = AccidentManagementConstant.EnvironmentFactor.get(Integer.parseInt(s));
                    factors += factor;
                    factors += ",";
                }
                vo.setEnvironmentFactorStr(factors);
            }

            if(vo.getPersonFactor() != null){
                String[] arr = vo.getPersonFactor().split(",");
                String factors = "";
                for (String s : arr) {
                    String factor = AccidentManagementConstant.PersonFactor.get(Integer.parseInt(s));
                    factors += factor;
                    factors += ",";
                }
                vo.setPersonFactorStr(factors);
            }

            if(vo.getManageFactor() != null){
                String[] arr = vo.getManageFactor().split(",");
                String factors = "";
                for (String s : arr) {
                    String factor = AccidentManagementConstant.ManageFactor.get(Integer.parseInt(s));
                    factors += factor;
                    factors += ",";
                }
                vo.setManageFactorStr(factors);
            }

            String responsibleId = vo.getResponsibleId();
            String[] idList = responsibleId.split(",");
            String responsibleName = "";
            for (String s : idList) {
                SysUser user = userService.getById(Integer.parseInt(s));
                if(user == null){
                    continue;
                }else{
                    responsibleName += user.getName();
                    responsibleName += ",";
                }
            }
            vo.setResponsibleName(responsibleName);

            String personInvolved = vo.getPersonInvolved();
            String[] split = personInvolved.split(",");
            String personInvolvedName = "";
            for (String s : split) {
                SysUser user = userService.getById(Integer.parseInt(s));
                if(user == null){
                    continue;
                }else{
                    personInvolvedName += user.getName();
                    personInvolvedName += ",";
                }
            }
            vo.setPersonInvolvedName(personInvolvedName);

            SysUser creator = userService.getById(vo.getCreator());
            vo.setCreatorName(creator == null ? "该用户不存在" : creator.getName());

            Organization organization = organizationService.getById(vo.getDepartmentId());
            vo.setDepartmentName(organization == null ? "该部门不存在" : organization.getName());

            new_list.add(vo);
        });

        ExcelUtils.exportExcel(new_list,"未遂事件","未遂事件",MissAccidentVO.class,"未遂事件",response);
    }

}
